package com.esoon.smartsee;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.hardware.Camera;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.android.gl2jni.GL2JNIView;
//import com.android.gles.ViEAndroidGLES20;
import com.esoon.activity.LoginActivity;
import com.esoon.utils.AlertDialogCommon;
import com.mb.mbvoiplib.MBVoipGUIDB;
import com.mb.mbvoiplib.VideoPreview;
import com.mb.mediaengine.MBCamera;
import com.mb.mediaengine.MBCommand;
import com.mb.mediaengine.MBLayoutPosition;
import com.mb.mediaengine.MediaEngineVideoDB;
//import com.mb.mediaengine.hw.SmartSeeVideoRuntime;
import com.mb.voip.api.MBVoipClientApp;
import com.mb.voip.api.VTCallStateListener;
import com.mb.voip.api.VideoPhone;
import com.mb.voip.api.VideoPhoneDataBean;
import com.mb.voip.api.mbVTCallsManager;

import java.text.DecimalFormat;
import java.util.List;

public class VideoActivity extends AppCompatActivity implements
        SurfaceHolder.Callback,
        VideoPhone.VTRemoteVideoNotify,
        VideoPhone.VTLocalVideoNotify, VideoPhone.VTMessageNotify,
        MBCamera.MBCallback {//implements MBCamera.MBCallback {
    SurfaceHolder mHolderPreview;
    GL2JNIView mGlView;
    RelativeLayout videolayout;
    ImageButton hungup;
    public int current_camera_id = 1;
    private static final String TAG = "VideoActivity";
    VideoPreview localSurface = null;
    public VideoPhone me;
    VTStateListener vtStateListener;
    static public int iRemoteWidth = 1280;
    static public int iRemoteHeight = 720;
    com.mb.voip.api.SmartSeeListener.VTVideoListener vtVideoListener = null;
    AlertDialogCommon dialog;
    static public int iLocalWidth = 0;
    static public int iLocalHeight = 0;
    double bili = 0;
    boolean bLocalSurfaceAdded = false;
    boolean b_opr_local = false;
    boolean bRemoteSurfaceAdded = false;
    boolean b_opr_remote = true;
    int remote_video_x;
    int remote_video_y;
    int remote_video_w;
    int remote_video_h;
    static Handler handler;
    DisplayMetrics dm2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_tab);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                switch (msg.what) {
                    case 1:
                        if (mGlView == null) {
                            mGlView = new GL2JNIView(getApplicationContext());
                            MBLayoutPosition pos3 = MediaEngineVideoDB.GetViewsLayoutPos(0, 0,
                                    dm2.widthPixels, Double.valueOf(dm2.widthPixels * bili).intValue());
                            AddSurfaceIntoView(pos3, mGlView, true, true);
                            mGlView.setZOrderOnTop(false);
                            bRemoteSurfaceAdded = true;
                        }


                        break;


                }

            }
        };

        videolayout = findViewById(R.id.videolayout);

        dialog = new AlertDialogCommon(this, R.layout.layout_dialog);
        hungup = dialog.getView().findViewById(R.id.hungup);

        hungup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MBVoipClientApp client = MBVoipClientApp.getVoipClientApp();
                mbVTCallsManager callsManager = mbVTCallsManager.getManager();
                int callid = callsManager.getActiveCallId();
                client.DropCall(callid);
                dialog.dismiss();

            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.showDialog();

        Camera mCamera = Camera.open();
        Camera.Parameters params = mCamera.getParameters();

        List<Camera.Size> pictureSizes = params.getSupportedPictureSizes();
        int length = pictureSizes.size();
        for (int i = 0; i < length; i++) {
            Log.e("SupportedPictureSizes", "SupportedPictureSizes : " + pictureSizes.get(i).width + "x" + pictureSizes.get(i).height);
        }

        mCamera.release();
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        Log.w(TAG, "VoipVideoCalling onCreate vt display metrics heigth : " + dm.heightPixels);
        Log.w(TAG, "VoipVideoCalling onCreate vt display metrics width : " + dm.widthPixels);
        me = VideoPhone.getVideoPhone();
        dm2 = getResources().getDisplayMetrics();
        Log.w(TAG, "vt display resource heigth: " + dm2.heightPixels);
        Log.w(TAG, "vt display resource width : " + dm2.widthPixels);

        iRemoteWidth = dm2.widthPixels;
        iRemoteHeight = dm2.heightPixels;

        Display display = getWindowManager().getDefaultDisplay();
        Log.w(TAG, "vt display width:" + display.getWidth());
        Log.w(TAG, "vt display height :" + display.getHeight());

        int isOver = getIsOver180(display);
        MediaEngineVideoDB.setScreenSize(dm.widthPixels, dm.heightPixels,
                isOver);
        MediaEngineVideoDB.iUsedCameraId = current_camera_id;
//        SmartSeeVideoRuntime.bHardwareEncoder = false;
//        if (MediaEngineVideoDB.mEnableHardwareEncoder == true)
//            SmartSeeVideoRuntime.bHardwareEncoder = true;
        localSurface = new VideoPreview(VideoActivity.this);
        localSurface.SetCB(VideoActivity.this);
        mHolderPreview = localSurface.getHolder();
//        localSurface.SetCB(VideoActivity.this);
        mode1();

        vtStateListener = new VTStateListener(this);
        me.registerVTCallStateChangeListener(vtStateListener);
        vtVideoListener = new SmartSeeVideoListener(this);
        me.registerVTVideoListener(vtVideoListener);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);


        VideoPhone.RegisterRemoteVideoNotify(this);
        VideoPhone.RegisterLocalVideoNotify(this);
        VideoPhone.RegisterLocalMessageNotify(this);


    }

    public void mode3() {
        int w = iLocalWidth;
        int h = iLocalHeight;
        int screenw = MediaEngineVideoDB.iScreenWidth / 2;
        int screenh = MediaEngineVideoDB.iScreenHeight;

        int nextLeft = screenw;
        int nextTop = 0;
        MBLayoutPosition pos = MediaEngineVideoDB.GetViewsLayoutPos(w, h,
                screenw, screenh);

        pos.left = pos.left + nextLeft;
        pos.top = pos.top + nextTop;
        AddSurfaceIntoView(pos, localSurface, true, true);
        localSurface.setZOrderOnTop(true);
        bLocalSurfaceAdded = true;
        localSurface.enableMove = false;
        localSurface.enableZoom = true;


        pos = MediaEngineVideoDB.GetViewsLayoutPos(iRemoteWidth, iRemoteHeight,
                screenw, screenh);

        if (MBCamera.bMotionDetection == 1) {
            pos.left = 0;
            pos.top = 0;
            remote_video_x = 0;
            remote_video_y = 0;
            remote_video_w = pos.width;
            remote_video_h = pos.height;
        }

        if (mGlView == null)
            mGlView = new GL2JNIView(getApplication());
        AddSurfaceIntoView(pos, mGlView, true, true);
        mGlView.setZOrderOnTop(false);
        //AddSurfaceIntoView(pos, remoteSurface, true, true);
        //remoteSurface.setZOrderOnTop(false);
        bRemoteSurfaceAdded = true;
    }

    public void mode2() {
        int w = iLocalWidth;
        int h = iLocalHeight;
        int gapAlign = MediaEngineVideoDB.iScreenWidth / 10;
        int gapVlign = MediaEngineVideoDB.iScreenHeight / 10;
        int fullwidth = MediaEngineVideoDB.iScreenWidth / 10 * 8;
        int fullheight = MediaEngineVideoDB.iScreenHeight / 10 * 8;
        MBLayoutPosition pos = MediaEngineVideoDB.GetViewsLayoutPos(w, h,
                fullwidth, fullheight);
        pos.top += (MediaEngineVideoDB.iScreenHeight / 10);
        pos.left += (MediaEngineVideoDB.iScreenWidth / 10);

        AddSurfaceIntoView(pos, localSurface, true, false);

        localSurface.setZOrderOnTop(true);
        bLocalSurfaceAdded = true;
        localSurface.enableMove = false;
        localSurface.enableZoom = true;


        pos = MediaEngineVideoDB.GetViewsLayoutPos(iRemoteWidth, iRemoteHeight,
                MediaEngineVideoDB.iScreenWidth / 4, MediaEngineVideoDB.iScreenHeight / 4);

        pos.left = pos.left + MediaEngineVideoDB.iScreenWidth / 4 * 3 - gapAlign;
        pos.top = pos.top + MediaEngineVideoDB.iScreenHeight / 4 * 3 - gapVlign;
        if (mGlView == null)
            mGlView = new GL2JNIView(getApplication());
        AddSurfaceIntoView(pos, mGlView, true, true);
        mGlView.setZOrderOnTop(true);
        //AddSurfaceIntoView(pos, remoteSurface, true, true);
        //remoteSurface.setZOrderOnTop(true);
        bRemoteSurfaceAdded = true;

    }


    public void mode1() {
        int w = iLocalWidth;
        int h = iLocalHeight;
        int gapAlign = MediaEngineVideoDB.iScreenWidth / 10;
        int gapVlign = MediaEngineVideoDB.iScreenHeight / 10;
        //必须加上才会出图像
        MBLayoutPosition pos2 = MediaEngineVideoDB.GetViewsLayoutPos(w, h,
                MediaEngineVideoDB.getiPreviewWidth(), MediaEngineVideoDB.getiPreviewHeight());

//      pos2.width=iRemoteWidth;
//      pos2.height=iRemoteHeight;
        pos2.left =  MediaEngineVideoDB.iScreenWidth /4*3 ;
        pos2.top =  MediaEngineVideoDB.iScreenHeight /4*3 ;

        AddSurfaceIntoView(pos2, localSurface, true, true);

        localSurface.setZOrderOnTop(true);
        localSurface.enableMove = false;
        localSurface.enableZoom = true;
        bLocalSurfaceAdded = true;


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dialog.dismiss();
    }


    public class SmartSeeVideoListener implements com.mb.voip.api.SmartSeeListener.VTVideoListener {
        private VideoActivity vp;

        public SmartSeeVideoListener(VideoActivity phone) {
            vp = phone;
        }

        @SuppressLint("WrongConstant")
        public void onRemoteResolutionChanged(int w, int h, int params) {
            Log.w(TAG, "onRemoteResolutionChanged w=" + w + ",h=" + h + ",params=" + params);
            iRemoteWidth = w;
            iRemoteHeight = h;

            Intent intent = new Intent();// create intent object
            intent.setAction(MBCommand.MB_COMMAND_FILTER_CALLING_NAME);
            intent.setFlags(1);
            vp.sendBroadcast(intent);
        }

        public void onLocalResolutionChanged(int w, int h, int params) {

        }
    }


    public static int getIsOver180(Display display) {
        int orientation = display.getRotation();
        Log.e(TAG, "rotation orientation[" + orientation + "]");
        int isOver = 0;
        switch (orientation) {
            case Surface.ROTATION_0:
            case Surface.ROTATION_90:
                isOver = 0;
                break;
            case Surface.ROTATION_180:
            case Surface.ROTATION_270:
                isOver = 1;
                break;
        }

        return isOver;
    }

    private class VTStateListener implements VTCallStateListener {
        private VideoActivity vp;

        public VTStateListener(VideoActivity phone) {
            vp = phone;
        }

        public void onVTCallStateChanged(VideoPhone vt, int callId, int state, int param3, int param4,
                                         Object param) {
            if (vt == null)
                return;

            switch (state) {
                case VideoPhoneDataBean.MBVoipCall_Disonnected:
                    Log.w(TAG, "get disconnect message");
//                    me.jniDropGLView();
                    // dismissPopWindow();
                    //VTReceiverStop();
                    MBVoipGUIDB.vtCallingIntent = null;
                    //  destroy();
                    finish();
                    break;
            }


        }
    }

    private void AddSurfaceIntoView(MBLayoutPosition pos,
                                    SurfaceView sur, boolean bAddPopupListen, boolean bSetFront) {
        if (pos.width > 0 && pos.height > 0) {
            if (sur != null) {
                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                        pos.width, pos.height);
                params.leftMargin = pos.left;
                params.topMargin = pos.top;
                videolayout.addView(sur, params);
                if (bAddPopupListen)
                    // addPopupToolListenerIntoSurface(sur);
                    sur.setVisibility(SurfaceView.VISIBLE);
                if (bSetFront) {
                    videolayout.bringChildToFront(sur);
                    sur.bringToFront();
                }
            }
        }
    }

    @Override
    public void drawVideoNotify(int id, int width, int height) {
        //	Log.e(LOG_TAG, "drawVideoNotify id="+id+",width="+width+",height="+height);
        if (MediaEngineVideoDB.bShowPreviewInDisplay == 1) {
            return;
        }

        if (iRemoteWidth != width) {

            //resize mGLView position
            iRemoteWidth = width;
            iRemoteHeight = height;
            Log.e("width is :", "" + width);
            Log.e("height is :", "" + height);
            bili = (double) height / width;
            Log.e("rate is :", "" + bili);
            Message message = new Message();
            message.what = 1;
            handler.sendMessage(message);
        }
        if (mGlView != null) {
            mGlView.RequestRender();
        }
    }

    @Override
    public int recv_fast_update(int callid, int channelid) {

        return -1;
    }

    @Override
    public int change_send_bitrate(int callid, int bitrate, int w, int h) {
        ;
        return -1;
    }

    //VTLocalVideoNotify Callback End
    //VTMessageNotify callback start
    public int recv_message(int callid, String content) {
        // Toast.makeText(VideoActivity.this, content, 1).show();
        return 0;
    }

    // MBCamera.MBCallback callback start
    public static boolean bAutoFocusCamera = true;

    public void onFristFrame(int type) {
        if (bAutoFocusCamera && type == 0) // raw video preview callback
        {
            // send caemra focus command
            //   sentBroadCommand(MBCommand.MB_COMMAND_AUTOFOCUS_CAMERA);
        }
    }

    public void onFindMotion(int flag) {
        if (flag > 0) {
            // sentBroadCommand(MBCommand.MB_COMMAND_FLASH_CAMERA);
        }
        //    Log.w(LOG_TAG, "onFindMotion flag=" + flag);
    }

    public void surfaceCreated(SurfaceHolder holder) {

    }

    public void surfaceDestroyed(SurfaceHolder holder) {
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {


    }
//    @Override
//    public void onFristFrame(int i) {
//
//    }
//
//    @Override
//    public void onFindMotion(int i) {
//
//    }
}
